package com.ftg.learn.sys.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.comm.entity.sys.Role;
import com.ftg.learn.comm.entity.sys.RoleResources;
import com.ftg.learn.sys.user.mapper.RoleMapper;
import com.ftg.learn.sys.user.mapper.RoleResourcesMapper;
import com.ftg.learn.sys.user.service.IRoleService;
import com.ftg.learn.util.ResBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 角色表，用来存储当前系统的角色 服务实现类
 * </p>
 *
 * @author kangjx
 * @since 2022-10-30
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {


    @Resource
    RoleMapper roleMapper;

    @Resource
    RoleResourcesMapper roleResourcesMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResBean deleteRoleWithResource(Integer id) {

        Role role = roleMapper.selectById(id);
        if(Objects.isNull(role)){
            return ResBean.noData();
        }

        // 中间表
        UpdateWrapper<RoleResources> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("r_id",id);
        roleResourcesMapper.delete(updateWrapper);
        //本表
        roleMapper.deleteById(id);

        return ResBean.success();
    }


    /**
     * 由于我们本身是对权限进行批量操作，添加角色权限中间表
     *    权限表里面的数据量有限所以可以采用 for来做
     *    如果是大量业务
     *    insert into sys_role_rescourse values(),(),(),(),(),()
     * @param rid
     * @param resids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResBean roleWithResource(Integer rid, List<Integer> resids) {
        Role role = roleMapper.selectById(rid);
        if(Objects.isNull(role)){
            return ResBean.noData();
        }

        if(Objects.isNull(resids)){
            return ResBean.failInvalidParam();
        }

        //原始的授权去掉，只保留本次授权
        QueryWrapper<RoleResources> query = new QueryWrapper<>();
        query.eq("r_id",rid);
        roleResourcesMapper.delete(query);

        //添加中间表
        for (Integer resid : resids) {
            RoleResources roleResources = new RoleResources();
            roleResources.setRid(rid);
            roleResources.setResId(resid);
            roleResourcesMapper.insert(roleResources);
        }
        return ResBean.success();
    }
}
